package com.lesson22.utils;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
 * 对称加密
 * 非对称加密
 * 
 * @author 2230
 *
 */
public class AesUtils {

	/**
	 * 生成key，作为加密和解密密钥且只有密钥相同解密加密才会成功
	 * @return
	 */
	public static Key createKey() {
		try {
			// 生成key
			KeyGenerator keyGenerator;
			//构造密钥生成器，指定为AES算法,不区分大小写
			keyGenerator = KeyGenerator.getInstance("AES");
			//生成一个128位的随机源,根据传入的字节数组
			keyGenerator.init(128);
			//产生原始对称密钥
			SecretKey secretKey = keyGenerator.generateKey();
			//获得原始对称密钥的字节数组
			byte[] keyBytes = secretKey.getEncoded();
			// key转换,根据字节数组生成AES密钥
			Key key = new SecretKeySpec(keyBytes, "AES");
			return key;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * 加密
	 * 
	 * @param context 需要加密的明文
	 * @param key 加密用密钥
	 * @return
	 */
	public static byte[] ecrypt(String context, String key) {
		try {
			SecretKeySpec skey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");  
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(cipher.ENCRYPT_MODE, skey);
			//将加密并编码后的内容解码成字节数组
			byte[] result = cipher.doFinal(context.getBytes());
			System.out.println("jdk aes:" + Base64.getEncoder().encode(result));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/** 
	 * 解密
	 * @param result 加密后的密文byte数组
	 * @param key 解密用密钥
	 */
	public static String decrypt(byte[] ecryptDate, String key) {
		Cipher cipher;
		byte[] result = null;
		try {
			SecretKeySpec skey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");  
			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			//初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
			cipher.init(Cipher.DECRYPT_MODE, skey);
			result = cipher.doFinal(ecryptDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String(result);
	}
	
	public static void main(String[] args) {
		Key key =  createKey();
		String keyStr = Base64.getEncoder().encodeToString(key.getEncoded());
		System.out.println(keyStr);
		//hq0BL7XCPDtno6lykvO6kw==
		byte[] ecrypt = ecrypt("111111huang打發", keyStr);
		System.out.println(new String(ecrypt));
		String decrypt = decrypt(ecrypt, keyStr);
		System.out.println(decrypt);
	}
	
	
	
}
